import {mapGetters, mapMutations, mapActions} from 'vuex'
import {playMode} from 'common/js/config'
import {shuffle} from 'common/js/util'


export const playlistMixin = {
  computed: {
    ...mapGetters([
      'playlist'
    ])
  },
  mounted() {
    this.handlePlaylist(this.playlist)
  },
  activated() {
    this.handlePlaylist(this.playlist)
  },
  watch: {
    playlist(newVal) {
      this.handlePlaylist(newVal)
    }
  },
  methods: {
    handlePlaylist() {
      throw new Error('component must implement handlePlaylist method')
    }
  }
}

export const playerMixin = {
  computed: {
    iconMode() {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    },
    ...mapGetters([
      'sequenceList',
      'playList',
      'currentSong',
      'mode',
      'favoriteList',
      'favoriteSong'
    ])
  },
  methods: {
    //切换 播放模式
    changeMode() {
      const mode =(this.mode+ 1) % 3
      this.setPlayMode(mode)
      let list=null
      if(mode===playMode.random){
        list=shuffle(this.sequenceList)
      }else{
        list=this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    resetCurrentIndex(list) {
      let index=list.findIndex((item)=>{
         return item.id===this.currentSong.id
      })
      this.setCurrentIndex(index)
    },
    setFavoriteIcon(song) {
      if(this.isFavorite(song)) {
        return 'icon-favorite'
      }else{
         return 'icon-not-favorite'
      }
    },
    getFavoriteState(song) {
      if(this.isFavorite(song)) {
        this.delFavorite(song)
      }else {
        this.saveFavorite(song)
      }
      
    },
    isFavorite(song) {
      let index=this.favoriteSong.findIndex(item=> {
        return item.id=== song.id
      })
      return index > -1
    },
     //Mutation
     ...mapMutations({
      setFullscreen:"SET_FULL_SCREEN",
      setPlaying:'SET_PLAYING',
      setCurrentIndex:'SET_CURRENT_INDEX',
      setPlayMode:'SET_PLAYING_MODE',
      setPlayList:'SET_PLAYING_LIST',

    }),
    ...mapActions([
      'saveFavorite',
      'delFavorite'
    ])

  }
}

export const searchMixin = {
  data() {
    return {
      query: ''
    }
  },
 methods: {
   // 把点击的热门数据 传给search-box 显示在输入框中
  addQuery(query){
    this.$refs.searchBox.setQuery(query)
  },
  // search-box传递过来的
  onQueryChange(query) {
    this.query=query
  },
  blurInput() {
    this.$refs.searchBox.blur()
  },
  //suggest列表歌曲被点击，保存下来
  saveHistory() {
    this.saveSearchHistory(this.query)
  },
  delItem(item) {
    this.delOneSearchHistory(item)
  },
  ...mapActions([
    'saveSearchHistory',
    'delOneSearchHistory'
  ]),
 }
}
